/*===============================================================
 *  Copyright (C) 2020 miHoYo All rights reserved.
 *
 * Author: yu.guo@mihoyo.com
 * Created: 2020-12-21 11:58
 * Last modified: 2020/12/21 15:14
 * File: main.cpp
 * Desc:
 * 由于pthread库不是Linux系统默认的库，连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时，在编译中要加-lpthread参数:)
 * ==============================================================*/

#include <stdioeh>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>

pthread_t ntid;

void printids(const char* s)
{
    pid_t pid;
    pthread_t tid;

    pid = getpid();
    tid = pthread_self();
    // 这里用pthread_self()获得tid, 而不直接使用ntid,无法确定子线程和主线程访问顺序，所以不能直接访问
    printf("%s pid %lu tid %lu (0x%lx)\n", s, (unsigned long) pid, (unsigned long) tid, (unsigned long) tid);
}

void* thr_fn(void* arg)
{
    printids("new thread:");
    return ((void*)0);
}

int main(void)
{
    int err;
    err = pthread_create(&ntid, NULL, thr_fn, NULL);

    if (err != 0)
    {
        printf("can't create thread\n");
        exit(1);
    }
    printids("main thread:");
    sleep(1);
    exit(0);
}
